/*
 PFDViewController.m
 LegislatorLookup
 
 The class controls the Personal Financial Disclosure View.
 
 Copyright (c) 2009 Nabil Ahmad
 All rights reserved.
 
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 
 1. Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.
 
 2. Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in the 
 documentation and/or other materials provided with the distribution. 
 
 3. The name of the author may not be used to endorse or promote products
 derived from this software without specific prior written permission.
 
 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */	

#import "PFDViewController.h"
#import "WebServiceController.h"

#define LABEL_TAG 1
#define VALUE_TAG 2
#define FIRST_CELL_IDENTIFIER @"FIRST_CELL"

#define SUMMARY_SECTION 0
#define POSITION_SECTION 1
#define ASSET_SECTION 2

@implementation PFDViewController

// custom init method
- (id) initWithCandidateId:(NSString *)candId {
	[super initWithStyle:UITableViewStyleGrouped];
	candidateId = candId;
	return self;
}

- (void)loadView {
	[super loadView];
	self.title = @"Personal Financial Disclosure";
	isDataLoaded = NO;
}

// load data and rerender view after view is loaded
- (void)viewDidAppear:(BOOL)animated
{
	// load data
	disclosureData = [[WebServiceController getPFDStatement:candidateId] retain];
	isDataLoaded = YES;
	// make data is being returned properly
	if (disclosureData == nil)
		dataError = YES;
	else
		dataError = NO;
	
	// Footer
	CGRect footerRect = CGRectMake(0, 0, 320, 30);
    UILabel *footerText = [[UILabel alloc] initWithFrame:footerRect];
    footerText.textColor = [UIColor grayColor];
    footerText.backgroundColor = [UIColor clearColor];
    footerText.opaque = YES;
    footerText.font = [UIFont systemFontOfSize:12];
	footerText.textAlignment = UITextAlignmentCenter;
	footerText.numberOfLines = 0;	
    self.tableView.tableFooterView = footerText;
    
	// Use footer for error message
	if (!dataError)
		footerText.text = [NSString stringWithFormat:@"Content provided by %@",[[disclosureData objectForKey:@"@attributes"] objectForKey:@"origin"]];
	else
		footerText.text = @"Either this information is not available for this candidate or there has been an error accessing the data";		
	
    [footerText release];	
	[self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	if (!dataError && isDataLoaded)
		return  3;
	else 
		return 1;
}

// return rows relative to section
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
	int rows = 0;
	
	if (!dataError && isDataLoaded) {
		if (SUMMARY_SECTION == section)
			rows = 2;
		else if (POSITION_SECTION == section)
		{
			rows = [[[disclosureData objectForKey:@"positions"] objectForKey:@"position"] count];
		}
		else if (ASSET_SECTION == section)
			rows = [[[disclosureData objectForKey:@"assets"] objectForKey:@"asset"] count];
	}
	
	return rows;
}
// return cell with two sub-rows
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:FIRST_CELL_IDENTIFIER];
	UILabel *label, *value;
	
	if (cell == nil) {
		
		CGRect frame = CGRectMake(0, 0, 300, 50);	
		cell = [[[UITableViewCell alloc] initWithFrame:frame reuseIdentifier:FIRST_CELL_IDENTIFIER] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		
		label = [[[UILabel alloc] initWithFrame:CGRectMake(5.0, 5.0, 295, 16)] autorelease];
		label.tag = LABEL_TAG;
		label.font = [UIFont boldSystemFontOfSize:12.0];
		label.textAlignment = UITextAlignmentLeft;
		label.textColor = [UIColor grayColor];
		label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
		[cell.contentView addSubview:label];
		
		value = [[[UILabel alloc] initWithFrame:CGRectMake(5.0, 24, 295, 16)] autorelease];
		value.tag = VALUE_TAG;
		value.font = [UIFont boldSystemFontOfSize:12.0];
		value.textColor = [UIColor blackColor];
		value.textAlignment = UITextAlignmentLeft;
		value.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
		[cell.contentView addSubview:value];
	} else {
		label = (UILabel *)[cell.contentView viewWithTag:LABEL_TAG];	
		value = (UILabel *)[cell.contentView viewWithTag:VALUE_TAG];
	}
	
	NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
	[numberFormatter setPositiveFormat:@"$#,##0"];
	[numberFormatter setNegativeFormat:@"$#,##0"];
	
	NSString *rowLabel = @"";
	NSString *rowValue = @"";
	
	if (SUMMARY_SECTION == indexPath.section)
	{
		if (indexPath.row == 0)
		{
			int nwLow = [[[disclosureData objectForKey:@"@attributes"] objectForKey:@"net_low"] intValue];
			int nwHigh = [[[disclosureData objectForKey:@"@attributes"] objectForKey:@"net_high"] intValue]; 

			rowLabel = @"Net Worth";
			rowValue = [NSString stringWithFormat:@"%@ - %@",[numberFormatter stringFromNumber:[NSNumber numberWithInt:nwLow]], [numberFormatter stringFromNumber:[NSNumber numberWithInt:nwHigh]]]; 
		}
		else
		{
			int asLow = [[[disclosureData objectForKey:@"@attributes"] objectForKey:@"asset_low"] intValue];
			int asHigh = [[[disclosureData objectForKey:@"@attributes"] objectForKey:@"asset_high"] intValue]; 
	
			rowLabel = @"Asset Value";
			rowValue = [NSString stringWithFormat:@"%@ - %@",[numberFormatter stringFromNumber:[NSNumber numberWithInt:asLow]], [numberFormatter stringFromNumber:[NSNumber numberWithInt:asHigh]]]; 
		}
	}
	else if (POSITION_SECTION == indexPath.section)
	{
		int numRows = [[[disclosureData objectForKey:@"positions"] objectForKey:@"position"] count];
		if (numRows > 1) {
			rowLabel = [[[[[disclosureData objectForKey:@"positions"] objectForKey:@"position"] objectAtIndex:indexPath.row] objectForKey:@"@attributes"] objectForKey:@"organization"];
			rowValue = [[[[[disclosureData objectForKey:@"positions"] objectForKey:@"position"] objectAtIndex:indexPath.row] objectForKey:@"@attributes"] objectForKey:@"title"];
		} else if (numRows == 1) {
			rowLabel = [[[[disclosureData objectForKey:@"positions"] objectForKey:@"position"] objectForKey:@"@attributes"] objectForKey:@"organization"];
			rowValue = [[[[disclosureData objectForKey:@"positions"] objectForKey:@"position"] objectForKey:@"@attributes"] objectForKey:@"title"];
		}
		else
		{
			rowLabel = @"None";
			rowValue = @"None";
		}
	}
	else if (ASSET_SECTION == indexPath.section)
	{
		NSDictionary *row = nil;
		if ([[[disclosureData objectForKey:@"assets"] objectForKey:@"asset"] count] > 1) {
			row = [[[[disclosureData objectForKey:@"assets"] objectForKey:@"asset"] objectAtIndex:indexPath.row] objectForKey:@"@attributes"];
		} else {
			row = [[[disclosureData objectForKey:@"assets"] objectForKey:@"asset"] objectForKey:@"@attributes"];
		}
			
		int asLow = [[row objectForKey:@"holdings_low"] intValue];
		int asHigh = [[row objectForKey:@"holdings_high"] intValue];
		
		rowLabel =  [row objectForKey:@"name"];
		rowValue = [NSString stringWithFormat:@"%@ - %@",[numberFormatter stringFromNumber:[NSNumber numberWithInt:asLow]], [numberFormatter stringFromNumber:[NSNumber numberWithInt:asHigh]]]; 
	}
		
		
	label.text = rowLabel;
	value.text = rowValue;

	return cell;
}

// return static row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
{	
	return 50;		
}

// return appropriate section header
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	NSString *title = nil;
	
	if (POSITION_SECTION == section)
		title = @"Positions Held";
	else if (ASSET_SECTION == section)
		title = @"Assets";
	
	return  title;
}

- (void)dealloc {
    [super dealloc];
	[disclosureData dealloc];
}


@end

